require(['config'], () => {
  require(['jquery', 'artTemplate', 'include', 'tools', 'zoom', 'cookie'], function ($, template) {
    class DetailPage {
      constructor() {
        this.details = {}
        this.renders()
        $.cookie.json = true
        this.bindEventListener()
        this.addEventListener()
      }
      renders () {
        const { id } = $.qsToObj(location.search.slice(1))
        console.log(id)
        $.ajax({
          url: 'http://www.xiongmaoyouxuan.com/api/detail',
          data: {
            id,
            normal: 1,
            sa: ''
          },
          success: (resData) => {
            this.details = resData.data.detail
            const { detail } = resData.data
            const html = template('right-template', { products: detail })
            $('.goods').append(html)
            this.addZoom()
          }
        })
      }
      addZoom () {
        $('.left_box img').elevateZoom({
          gallery: 'zoom-gal',
          galleryActiveClass: 'active'
        })
      }
      thisEvent (e) {
        console.log('in...');
        const src = $(e.target)
        let amount = Number(src.siblings('.numb').val())
        console.log(amount);
        console.log(src);
        if (src.is('.dels')) {
          if (amount <= 1) {
            return
          }
          amount -= 1
        } else {
          amount += 1
        }
        $('.numb').val(amount)
      }
      addEventListener () {
        $('main').on('click', '.add,.dels', this.thisEvent.bind(this))
      }
      bindEventListener () {
        $('main').on('click', '.huod', e => {
          e.preventDefault()

          console.log('加入购物车', this.details)
          const currentProduct = {
            id: this.details.id,
            title: this.details.title,
            price: Math.round(Number(this.details.price)),
            image: this.details.image,
            amount: Number($('.numb').val()),
            checked: true,
            keywords: this.details.keywords,
            qunTitle: this.details.qunTitle,
            introduction: this.details.introduction
          }
          const cart = $.cookie('cart') || []
          const has = cart.some(item => item.id === currentProduct.id)
          if (has) {
            for (let i = 0, len = cart.length; i < len; i++) {
              if (cart[i].id === currentProduct.id) {
                cart[i].amount += currentProduct.amount
                break
              }
            }
          } else {
            cart.push(currentProduct)
          }
          $.cookie('cart', cart, { expires: 10 })
          const tolal = cart.reduce((result, curr) => result + curr.amount, 0)
          $('.index-shopping .btn-shopping .gwc-shu .g-shu').html(tolal)
        })
      }
    }
    new DetailPage()
  })
})